<?php

###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ################




global $JFXMemDebug;
$JFXMemDebug[] = array('bytes'=>memory_get_usage(), 'file'=>__FILE__, 'line'=>__LINE__, 'time' => getmicrotime(), 'desc' => 'Entering edit.php');

if (get('classname') != '') {
	// have selected a class to edit
	$classname = preg_replace('/[^a-zA-Z0-9_\-]/', '', get('classname'));
	if (!$this->hasClassname($classname)) {
		JFX::addError($this->lang('invalid_classname_pattern'));
		JFX::redirect($this->adminUrl . '/edit/');
	}

	$JFXMemDebug[] = array('bytes'=>memory_get_usage(), 'file'=>__FILE__, 'line'=>__LINE__, 'time' => getmicrotime(), 'desc' => 'before making handler');

	// valid class to edit
	$handler = $this->getHandler($classname);

	$JFXMemDebug[] = array('bytes'=>memory_get_usage(), 'file'=>__FILE__, 'line'=>__LINE__, 'time' => getmicrotime(), 'desc' => 'after get handler');

	if (!isset($USER->JFX_Module_Blockstyle_Selectedtemplate)) {
		$USER->JFX_Module_Blockstyle_Selectedtemplate = 'default';
	}



	if (array_key_exists('ajaxCommand', $_GET) || array_key_exists('ajaxCommand', $_POST)) {
		$command = get('ajaxCommand', post('ajaxCommand'));

		switch ($command) {
			case 'set_template':
				$templateId = get('template_id');
				$block = JFX_Block::getBlockById($templateId, $SETTINGS->get('template_page_id'));
				if ($block instanceof JFX_Block) {
					$USER->JFX_Module_Blockstyle_Selectedtemplate = $templateId;
				}
			break;
			
			case 'show_preview':
				while (ob_get_level() > 0)
					ob_end_clean();


				$newView = new JFX_View();
				$newView->addCss('body{margin: 0; padding: 0;}p{margin: 0}' . "\n");
				$newView->template = $this->dirname . '/templates/show-preview.tpl';

				if ($USER->JFX_Module_Blockstyle_Selectedtemplate == 'default') {
					require($this->dirname.'/default-content.php');
					$content = '<div class="'.$classname.'">'.$defaultContent.'</div>';
					$IMAGE_MODULE = JFX::registry('JFX_Module_Imager');
					$outputCss = str_replace(':|imageUrl|:', $IMAGE_MODULE->imageUrl . '/serve.php', $handler->__toCss());
					$newView->addCss($outputCss);
				} else {
					$block = JFX_Block::getBlockById($USER->JFX_Module_Blockstyle_Selectedtemplate, $SETTINGS->get('template_page_id'), '', true, false);

					$doneStyles = array();
					$liveCss = JFX_Module_Blockstyle_Handler::getBlockCss($block, $doneStyles);

					$this->saveBlockCss($block->id, $liveCss);

					$newView->addCss($this->getBlockCss($block, true));
					$content = $block->render();
				}

				$newView->addBodyText($content);

				$newView->prepare();
				// check if cache is to be used or not - cache is off by default
				if (!$CONFIG->useSmartyCache || strlen($newView->cacheId) == 0) {
					// don't use caching
					$SMARTY->caching = 0;
					$pageAsString = $SMARTY->fetch($newView->template);
				} else {
					// use caching
					$SMARTY->caching = 2;
					$SMARTY->cache_lifetime = 86400;
					$pageAsString = $SMARTY->fetch($newView->template, $newView->cacheId);
				};

				die($pageAsString);

			break;

			case 'change_classname':
				$newClassname = get('newClassname');
				$handler = $this->getHandler($newClassname);
				if (is_object($handler) && $handler instanceof JFX_Module_Blockstyle_Handler) {
					//JFX::redirect($this->adminUrl.'/edit/?classname='.$newClassname.'&JFXGetAjaxContent=1');
					$classname = $newClassname;
				}
			break;

			case 'save_handler':
				$json = post('handler', '', 6000000);

				$handlerImport = json_decode($json);
				$handlerImport->classname = $classname;

				if (is_object($handlerImport)) {
					$handler->updateFromJson($handlerImport);

					if ($handler instanceof JFX_Module_Blockstyle_Handler) {
						$this->saveHandler($handler);
					} else {
						JFX::addError('Please report this problem!');
					}
				} else {
					throw new Exception('The json handler was not an object: ' . print_r($handlerImport, true));
				}
			break;

			case 'save_widget_property':
				$name = get('name');
				$value = get('value');
				$widgetInstanceId = get('widget_instance_id');
				$handler->setWidgetProperty($widgetInstanceId, $name, $value);
				$this->saveHandler($handler);
			break;

			case 'save_property_property':
				$name = get('name');
				$value = get('value');
				$propertyInstanceId = get('property_instance_id');
				$handler->setPropertyProperty($propertyInstanceId, $name, $value);
				$this->saveHandler($handler);
			break;

			case 'save_element_property':
				$name = get('name');
				$value = get('value');
				$elementId = get('element_id');
				$handler->setElementProperty($elementId, $name, $value);
				$this->saveHandler($handler);
			break;

			case 'save_handler_property':
				$name = get('name');
				$value = get('value');
				//$handler->$name = $value;
				$handler->setProperty($name, $value);
				$this->saveHandler($handler);
			break;

			case 'getCssOutput':
				while (ob_get_level() > 0) {
					ob_end_clean();
				}

				if ($USER->JFX_Module_Blockstyle_Selectedtemplate !== 'default') {
					$block = JFX_Block::getBlockById($USER->JFX_Module_Blockstyle_Selectedtemplate, $SETTINGS->get('template_page_id'), '', true, false);
					echo $this->getBlockCss($block, false);
				} else {
					echo $handler->__toCss();
				}


				exit;

			break;
		}
	}

	$handler->ajaxUrl = $this->adminUrl . '/edit/?classname=' . $classname . '&JFXGetAjaxContent=1';
	$handler->cssUrl = $this->adminUrl . '/edit/?classname=' . $classname . '&ajaxCommand=getCssOutput';
	$handler->previewUrl = $this->adminUrl . '/edit/?classname=' . $classname . '&ajaxCommand=show_preview';




	if ($USER->JFX_Module_Blockstyle_Selectedtemplate !== 'default') {
		$block = JFX_Block::getBlockById($USER->JFX_Module_Blockstyle_Selectedtemplate, $SETTINGS->get('template_page_id'), '', true, false);
		$outputCss = $this->getBlockCss($block, false);
	} else {
		$IMAGE_MODULE = JFX::registry('JFX_Module_Imager');
		$outputCss = str_replace(':|imageUrl|:', $IMAGE_MODULE->imageUrl . '/serve.php', $handler->__toCss());
	}

	$VIEW->addCss($outputCss);

	$allClassnames = $this->getAllClassnamesAsArray();

	foreach ($allClassnames as $k => $row) {
		$allClassnames[$k]['title'] = $this->getContentLang('title', $row['classname']);
	}

	$allTemplates = $CORE->getTemplatesAsArray();
	$templatesList = array();
	$count = 0;
	foreach ($allTemplates as $k => $block) {
		$templatesList[$count] = array(
		    'value' => $block->id,
		    'title' => JFX_Block::getTitleById($block->id, $block->pageid)
		);
		$count++;
	}

	$groupedElements = array();
	$handler->groupElements();

	foreach ($handler->groups as $groupId => $elementIds) {

		$group = JFX_Module_Blockstyle_Group_Base::getGroup($groupId);

		foreach ($elementIds as $elementId) {
			if (!array_key_exists($group->id, $groupedElements)) {
				$groupedElements[$group->id] = array(
				    'id' => $group->id,
				    'title' => $group->title,
				    'elements' => array($handler->getElement($elementId))
				);
			} else {
				$groupedElements[$group->id]['elements'][] = $handler->getElement($elementId);
			}
		}
	}

	$outputCss = htmlentities($outputCss);
	$outputCss = str_replace('	', '&nbsp;&nbsp;&nbsp;&nbsp;', $outputCss);
	$outputCss = str_replace(' ', '&nbsp;', $outputCss);
	$outputCss = str_replace('
', '<br />', $outputCss);

	$SMARTY->assign('allTemplates', $templatesList);
	$SMARTY->assign('selectedClassname', $classname);
	$SMARTY->assign('allClassnames', $allClassnames);
	$SMARTY->assign('selectedTemplate', $USER->JFX_Module_Blockstyle_Selectedtemplate);
	$SMARTY->assign('outputCss', $outputCss);
	$SMARTY->assign('handler_json', $handler->__toJson());
	$SMARTY->assign('handler', $handler);
	$SMARTY->assign('groupedElements', (array) $groupedElements);
	echo $this->fetchTemplate('edit-edit.tpl');
} else {
	// must select a class to edit
	$allClasses = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}{$this->keyname}_classnames ORDER BY sorting ASC");
	foreach ($allClasses as $k => $row) {
		$allClasses[$k]['title'] = $this->getContentLang('title', $row['classname']);
		$allClasses[$k]['url'] = $this->adminUrl . '/edit/?classname=' . $row['classname'];
	}
	$SMARTY->assign('classnames', $allClasses);
	echo $this->fetchTemplate('edit-select.tpl');
}





